<?php

namespace app\admin\controller;

use think\Lang;

/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 控制器
 */
class Member extends AdminControl
{

    public function _initialize()
    {
        parent::_initialize();
        Lang::load(APP_PATH . 'admin/lang/' . config('default_lang') . '/member.lang.php');
    }

    /*
     ajax 上传图片

    */
    public function ajax_upload()
    {
        $file_type = array('0' => 'image/jpeg', '1' => 'image/jpg', '2' => 'image/png');
        if (in_array($_FILES['file']['type'], $file_type)) {
            $file_name = input('post.name');
            $upload_info = upload_qiniu('file');
            return $upload_info;
        } else {
            return $data['msg'] = 0;

        }
    }

    public function member()
    {
        $member_model = model('member');


        //会员级别
        $member_grade = $member_model->getMemberGradeArr();
        $search_field_value = input('search_field_value');
        $search_field_name = input('search_field_name');
        $condition = array();
        if ($search_field_value != '') {
            switch ($search_field_name) {
                case 'member_name':
                    $condition['member_name'] = array('like', '%' . trim($search_field_value) . '%');
                    break;
                case 'member_email':
                    $condition['member_email'] = array('like', '%' . trim($search_field_value) . '%');
                    break;
                case 'member_mobile':
                    $condition['member_mobile'] = array('like', '%' . trim($search_field_value) . '%');
                    break;
                case 'member_truename':
                    $condition['member_truename'] = array('like', '%' . trim($search_field_value) . '%');
                    break;
            }
        }
        $search_state = input('search_state');
        switch ($search_state) {
            case 'no_informallow':
                $condition['inform_allow'] = '2';
                break;
            case 'no_isbuy':
                $condition['is_buylimit'] = '0';
                break;
            case 'no_isallowtalk':
                $condition['is_allowtalk'] = '0';
                break;
            case 'no_memberstate':
                $condition['member_state'] = '0';
                break;
        }
        //会员等级
        $search_grade = intval(input('get.search_grade'));
        if ($search_grade > 0 && $member_grade) {
            if (isset($member_grade[$search_grade + 1]['exppoints'])) {
                $condition['member_exppoints'] = array('between', array($member_grade[$search_grade]['exppoints'], $member_grade[$search_grade + 1]['exppoints']));
            } else {
                $condition['member_exppoints'] = array('egt', $member_grade[$search_grade]['exppoints']);
            }
        }
        //时间
        $query_start_time = input('param.query_start_time');
        $query_end_time = input('param.query_end_time');
        $if_start_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_start_time);
        $if_end_time = preg_match('/^20\d{2}-\d{2}-\d{2}$/', $query_end_time);
        $start_unixtime = $if_start_time ? strtotime($query_start_time) : null;
        $end_unixtime = $if_end_time ? strtotime($query_end_time) : null;
        if ($start_unixtime || $end_unixtime) {
            $condition['member_addtime'] = array('between', array($start_unixtime, $end_unixtime));
        }
        //排序
        $order = trim(input('get.search_sort'));
        if (!in_array($order, array('member_logintime desc', 'member_loginnum desc'))) {
            $order = 'member_id desc';
        }
        $condition['member_type'] = 0;
        $member_list = $member_model->getMemberList($condition, '*', 10, $order);
        //整理会员信息
        if (is_array($member_list) && !empty($member_list)) {
            foreach ($member_list as $k => $v) {
                $member_list[$k]['member_addtime'] = $v['member_addtime'] ? date('Y-m-d H:i:s', $v['member_addtime']) : '';
                $member_list[$k]['member_logintime'] = $v['member_logintime'] ? date('Y-m-d H:i:s', $v['member_logintime']) : '';
                $member_list[$k]['member_grade'] = ($t = $member_model->getOneMemberGrade($v['member_exppoints'], false, $member_grade)) ? $t['level_name'] : '';
            }
        }
        $this->assign('member_grade', $member_grade);
        $this->assign('search_sort', $order);
        $this->assign('search_field_name', trim($search_field_name));
        $this->assign('search_field_value', trim($search_field_value));
        $this->assign('member_list', $member_list);
        $this->assign('query_start_time', $query_start_time);
        $this->assign('show_page', $member_model->page_info->render());

        $config = db('config')->where('code', 'qiniu_http')->find();
        $this->assign('http_name', $config['value']);

        $this->assign('filtered', $condition ? 1 : 0); //是否有查询条件

        $this->assign('enterprise_status', ['0' => '未认证', '1' => '待审核', '2' => '审核通过', '3' => '审核不通过']);
        $this->setAdminCurItem('member');
        return $this->fetch();
    }

    //企业认证
    public function enterprise_list()
    {
        $brand_model = model('enterprise');
        /**
         * 检索条件
         */
        if (!empty(input('param.member_name'))) {
            $condition['member_name'] = array('like', "%" . input('param.member_name') . "%");
        }
        if (!empty(input('param.search_brand_name'))) {
            $condition['enterprise_name'] = array('like', "%" . input('param.search_brand_name') . "%");
        }
        $enterprisetype = input('param.enterprisetype', '');

        if (!empty($enterprisetype)) {
            $condition['enterprise_type'] = intval($enterprisetype);
        }

        // $condition['member_type'] = 0;

        //判断是那种类型
        $type = input('param.type');
        switch ($type) {
            case 'lockup':
                //审核不通过
                $condition['m.enterprise_status'] = 3;
                $enterprise_list = $brand_model->getEnterpriseList($condition, "*", 10);
                break;
            case 'waitverify':
                //待审核
                $condition['m.enterprise_status'] = 1;
                $enterprise_list = $brand_model->getEnterpriseList($condition, "*", 10);
                break;
            default:
                $enterprise_list = $brand_model->getEnterpriseList($condition, "*", 10);
                break;
        }

        foreach ($enterprise_list as $key => $value) {
            $enterprise_list[$key]['enterprise_time'] = date('Y-m-d H:i:s', $value['enterprise_time']);
        }
        $this->assign('showpage', $brand_model->page_info->render());
        $this->assign('enterprise_list', $enterprise_list);
        $this->assign('enterprisetype_search', intval($enterprisetype));
        $this->assign('search_brand_name', trim(input('param.search_brand_name')));
        $this->assign('member_name', trim(input('param.member_name')));
        $this->assign('enterprise_status', ['0' => '未认证', '1' => '待审核', '2' => '审核通过', '3' => '审核不通过']);
        //企业类型
        $enterprisetype = db('enterprisetype')->where(['status' => 1])->select();
        $this->assign('enterprisetype', $enterprisetype);
        $this->setAdminCurItem('index');

        $type = input('param.type');
        if (!in_array($type, array('lockup', 'waitverify', 'allgoods'))) {
            $type = 'allgoods';
        }
        $this->assign('type', $type);
        $this->setAdminCurItem($type);
        return $this->fetch();
    }


    /**
     * Notes:用户给查看详情
     * User: shen
     * Date: 2020/5/21
     * Time: 14:22
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function enterprise_info()
    {

        $member_id = input('param.member_id');
        $enterprise_detail = db('member')->where(['member_id' => $member_id])->find();
        if ($enterprise_detail['invite_parent_code']) {
            $parent_member_info = db('member')->where('invite_code', $enterprise_detail['invite_parent_code'])->find();
            if ($parent_member_info) {
                if ($parent_member_info['member_type'] == 8) {
                    $enterprise_detail['member_da_name'] = $parent_member_info['enterprise_name'];
                } else {
                    $enterprise_detail['member_da_name'] = '未绑定';
                }

            } else {
                $enterprise_detail['member_da_name'] = '未绑定';
            }
        } else {
            $enterprise_detail['member_da_name'] = '未绑定';
        }
        $this->assign('joinin_detail', $enterprise_detail);

        $pic = json_decode($enterprise_detail['enterprise_license'], true);
        $this->assign('pic', $pic);

        $enterprise_type = db('enterprisetype')->where(['id' => $enterprise_detail['enterprise_type']])->find();
        $this->assign('name', $enterprise_type['name']);
        $config = db('config')->where('code', 'qiniu_http')->find();
        $this->assign('http_name', $config['value']);
        $this->assign('is_verify', false);
        $this->assign('detail', ['0' => '禁用', '1' => '启用']);
        return $this->fetch('enterprise_info');
    }

    /**
     * Notes:审核详细页
     * User: shen
     * Date: 2020/5/4
     * Time: 17:52
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function enterprise_detail()
    {
        $enterprise_model = model('enterprise');
        $member_id = input('param.member_id');
        $enterprise_detail = $enterprise_model->getEnterpriseDetail(array('member_id' => $member_id));
        $this->assign('joinin_detail', $enterprise_detail);

        $pic = json_decode($enterprise_detail['enterprise_license'], true);
        $this->assign('pic', $pic);
        $config = db('config')->where('code', 'qiniu_http')->find();
        $this->assign('http_name', $config['value']);
        $this->assign('is_verify', true);
        $this->assign('detail', ['0' => '禁用', '1' => '启用']);
        return $this->fetch('enterprise_detail');
    }

    /**
     * Notes:审核操作
     * User: shen
     * Date: 2020/5/4
     * Time: 17:56
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function enterprise_verify()
    {
        $member_id = input('param.member_id');
        $status = input('post.verify_state');
        $reason = input('post.joinin_message');

        $enterprise_info = db('member')->where(['member_id' => $member_id])->find();
        if ($status == 1) {
            db('member')->where(['member_id' => $member_id])->update(['enterprise_status' => 2]);

        } else {
            db('member')->where(['member_id' => $member_id])->update(['enterprise_status' => 3, 'reasons' => $reason]);

        }
        dsLayerOpenSuccess('审核成功');
    }

    /**
     * @description: 删除操作  @MrLiu
     */
    public function cancels()
    {
        $member_id = intval(input('param.member_id'));
        $status = db('member')->where(['member_id' => $member_id])->update(['enterprise_del' => 1]);
        if ($status === false) {
            ds_json_encode(10001, '删除失败');
        }
        ds_json_encode(10000, '删除成功');
    }

    /**
     * @description: 检车名称是否存在  @MrLiu
     * @return bool
     */
    protected function check_type_name($name)
    {
        $afficheTypeModel = new AfficheTypeModel();
        $data = $afficheTypeModel->getOneAfficheType(array('name' => $name));
        if (!empty($data)) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * Notes:后台添加用户
     * User: shen
     * Date: 2020/5/21
     * Time: 8:55
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function add()
    {
        if (!request()->isPost()) {
            #获取客户类型
            $enterprisetype_info = db('enterprisetype')->where(['status' => 1, 'enterprisetype_del' => 0])->select();
            $this->assign('enterprisetype_info', $enterprisetype_info);
            return $this->fetch();
        } else {
            //需要完善地方 1.对录入数据进行判断  2.对判断用户名是否存在
            $member_model = model('member');

            $code = input('post.operator_code');

            #如果添加了运营商编码
            if (!empty($code)) {
                #查询当前编码的运营商
                $member_info = db('member')->where(['invite_code' => $code])->find();
                $store_info = db('store')->where(['member_id' => $member_info['member_id']])->find();

                $parent_code = $member_info['invite_code']; #邀请人编码
                $invite_store_id = $store_info['store_id']; #父级id
                $invite_store_name = $store_info['store_name']; #父级名称
                $invite_name = $member_info['member_name']; #邀请人账号
                $invite_type = 2;

            } else {
                #入到默认运营商下面
                $store_info = db('store')->where('store_id', config('store_id'))->find();
                $member_info = db('member')->where(['member_id' => $store_info['member_id']])->find();

                $parent_code = $member_info['invite_code']; #邀请人编码

                $invite_store_id = config('store_id'); #父级id
                $invite_store_name = $store_info['store_name']; #父级名称
                $invite_name = $member_info['member_name']; #邀请人账号
                $invite_type = 2;
            }

            $enterprise_type_info = db('enterprisetype')->where(['id' => input('post.enterprise_type')])->find();

            $data = array(
                'member_client' => input('post.member_client'),
                'member_name' => input('post.member_name'),
                'member_password' => input('post.member_password'),
                'member_nickname' => input('post.member_nickname'),
                'customer_name' => input('post.customer_name'),
                'member_address' => input('post.member_address'),
                'member_detail_address' => input('post.member_detail_address'),
                'member_start_time' => input('post.start_time'),
                'member_paragraph' => input('post.member_paragraph'),
                'member_person' => input('post.member_person'),
                'member_person_tel' => input('post.member_person_tel'),
                'member_mobile' => input('post.member_name'),
                'member_avatar' => input('post.portrait'),
                'enterprise_type' => input('post.enterprise_type'),
                'enterprise_type_name' => $enterprise_type_info['name'],
                'contact_name' => input('post.contact_name'),
                'contact_phone' => input('post.contact_phone'),
                'member_sex' => input('post.member_sex'),
                'member_qq' => input('post.member_qq'),
                'member_wx' => input('post.member_wx'),
                'member_addtime' => TIMESTAMP,
                'member_loginnum' => 0,
                'inform_allow' => 1, //默认允许举报商品
                'invite_parent_code' => $parent_code,
                'invite_store_id' => $invite_store_id,
                'invite_store_name' => $invite_store_name,
                'invite_name' => $invite_name,
                'invite_type' => $invite_type,
                'is_background_add' => 1, #1是后台添加
            );

            // $member_validate = validate('member');
            // if (!$member_validate->scene('add')->check($data)){
            //     $this->error($member_validate->getError());
            // }
            $result = $member_model->addMember($data);


            if ($result) {
                #创建极光im 账号
                $post = [
                    'username' => 'kehu' . $data['member_name'],
                    'password' => $data['member_password'],
                    'nickname' => $data['member_name'],
                    'avatar' => 'http://33wang.douyinhot.com/cfe45202004231527382825.png',
                    'signature' => '',
                ];
                JmRegist($post);

                dsLayerOpenSuccess(lang('ds_common_op_succ'));
            } else {
                $this->error(lang('member_add_fail'));
            }
        }
    }

    public function edit()
    {
        //注：pathinfo地址参数不能通过get方法获取，查看“获取PARAM变量”
        $member_id = input('param.member_id');
        if (empty($member_id)) {
            $this->error(lang('param_error'));
        }
        $member_model = model('member');
        if (!request()->isPost()) {
            $condition['member_id'] = $member_id;
            $member_array = $member_model->getMemberInfo($condition);
            $this->assign('member_array', $member_array);
            #获取客户类型
            $enterprisetype_info = db('enterprisetype')->where(['status' => 1, 'enterprisetype_del' => 0])->select();
            $this->assign('enterprisetype_info', $enterprisetype_info);
            return $this->fetch();
        } else {
            $member_info = db('member')->where(['member_id' => $member_id])->find();
            $enterprise_type_info = db('enterprisetype')->where(['id' => input('post.enterprise_type')])->find();

            $member_address = input('post.member_address');
            if (empty($member_address)) {
                $member_address = $member_info['member_address'];
            }
            $member_start_time = input('post.start_time');
            if (empty($member_start_time)) {
                $member_start_time = $member_info['member_start_time'];
            }
            $data = input('post.');

            $data = array(
                'member_client' => input('post.member_client'),
                'customer_name' => input('post.customer_name'),
                'member_address' => $member_address,
                'member_nickname' => input('post.member_nickname'),
                'member_detail_address' => input('post.member_detail_address'),
                'member_start_time' => $member_start_time,
                'member_paragraph' => input('post.member_paragraph'),
                'member_person' => input('post.member_person'),
                'member_person_tel' => input('post.member_person_tel'),
                'enterprise_type' => input('post.enterprise_type'),
                'enterprise_type_name' => $enterprise_type_info['name'],
                'contact_name' => input('post.contact_name'),
                'contact_phone' => input('post.contact_phone'),
                'member_wx' => input('post.member_wx'),
                // 'member_email' => input('post.member_email'),
                // 'member_truename' => input('post.member_truename'),
                'member_sex' => input('post.member_sex'),
                'member_qq' => input('post.member_qq'),
                'member_client' => input('post.member_client'),
                // 'member_ww' => input('post.member_ww'),
                'inform_allow' => input('post.inform_allow'),
                'is_buylimit' => input('post.isbuy'),
                'is_allowtalk' => input('post.allowtalk'),
                'member_state' => input('post.memberstate'),
                'member_cityid' => input('post.city_id'),
                'member_provinceid' => input('post.province_id'),
                'member_areainfo' => input('post.region'),
                'member_areaid' => input('post.area_id'),
                // 'member_mobile' => input('post.member_mobile'),
                'member_emailbind' => input('post.memberemailbind'),
                'member_mobilebind' => input('post.membermobilebind'),
                'enterprise_status' => input('post.member_auth_state'),
                'member_points' => input('post.member_points'),
            );

            if (input('post.member_password')) {
                $data['member_password'] = md5(input('post.member_password'));
            }
            if (input('post.member_paypwd')) {
                $data['member_paypwd'] = md5(input('post.member_paypwd'));
            }

            //如果修改上级运营商
            $code = input('post.operator_code');
            if (!empty($code)) {
                //通过code找到上级运营商
                $superior_info = db('member')->where(['invite_code' => $code])->find();
                if ($superior_info) {
                    $store_info = db('store')->where(['member_id' => $superior_info['member_id']])->find();
                    $data['invite_parent_code'] = $code;
                    $data['supplier_type'] = $superior_info['supplier_type'];
                    $data['invite_store_id'] = $store_info['store_id'];
                    $data['invite_store_name'] = $store_info['store_name'];
                    $data['invite_name'] = $store_info['member_name'];
                    $data['invite_type'] = $superior_info['member_type'];
                    $data['update_invite_store_time'] = time();
                }
            }

            //如果修改上级大客户
            $member_da_code = input('post.member_da_code', '');
            if ($member_da_code) {
                //通过code找到上级运营商
                $member_ds_info = db('member')->where(['invite_code' => $member_da_code, 'member_type' => 8])->find();
                if ($member_ds_info) {
                    $data['invite_parent_code'] = $member_da_code;
                }
                if (!$member_info['invite_store_id'] && !isset($data['invite_parent_code'])) {
                    $update_data['invite_store_id'] = config('store_id');
                }
            }
            $member_validate = validate('member');
            if (!$member_validate->scene('edit')->check($data)) {
                $this->error($member_validate->getError());
            }

            $result = $member_model->editMember(array('member_id' => intval($member_id)), $data);
            if ($result >= 0) {
                dsLayerOpenSuccess(lang('ds_common_op_succ'));
            } else {
                $this->error(lang('ds_common_op_fail'));
            }
        }
    }


    /**
     * ajax操作
     */
    public function ajax()
    {
        $branch = input('param.branch');

        switch ($branch) {
            /**
             * 验证会员是否重复
             */
            case 'check_user_name':
                $member_model = model('member');
                $condition['member_name'] = input('param.member_name');
                $condition['member_id'] = array('neq', intval(input('get.member_id')));
                $list = $member_model->getMemberInfo($condition);
                if (empty($list)) {
                    echo 'true';
                    exit;
                } else {
                    echo 'false';
                    exit;
                }
                break;
            /**
             * 验证邮件是否重复
             */
            case 'check_email':
                $member_model = model('member');
                $condition['member_email'] = input('param.member_email');
                $condition['member_id'] = array('neq', intval(input('param.member_id')));
                $list = $member_model->getMemberInfo($condition);
                if (empty($list)) {
                    echo 'true';
                    exit;
                } else {
                    echo 'false';
                    exit;
                }
                break;
            /**
             * 验证运营商编码
             */
            case 'check_operator_code':
                $member_model = model('member');
                $condition['invite_code'] = input('param.operator_code');
                $list = $member_model->getMemberInfo($condition);
                if (empty($list)) {
                    echo 'true';
                    exit;
                } else {
                    echo 'false';
                    exit;
                }
                break;
        }
    }

    /**
     * 设置会员状态
     */
    public function memberstate()
    {
        $member_id = input('param.member_id');
        $member_id_array = ds_delete_param($member_id);
        if ($member_id_array == FALSE) {
            ds_json_encode('10001', lang('param_error'));
        }
        $data['member_state'] = input('param.member_state') ? input('param.member_state') : 0;

        $condition = array();
        $condition['member_id'] = array('in', $member_id_array);
        $result = db('member')->where($condition)->update($data);
        if ($result >= 0) {
            foreach ($member_id_array as $key => $member_id) {
                dcache($member_id, 'member');
            }
            $this->log(lang('ds_edit') . '[ID:' . implode(',', $member_id_array) . ']', 1);
            ds_json_encode('10000', lang('ds_common_op_succ'));
        } else {
            ds_json_encode('10001', lang('ds_common_op_fail'));
        }
    }

    /**
     * 获取卖家栏目列表,针对控制器下的栏目
     */
    protected function getAdminItemList()
    {
        $menu_array = array(
            array(
                'name' => 'member',
                'text' => lang('ds_manage'),
                'url' => url('Member/member')
            ),
            // array(
            //     'name' => 'allgoods',
            //     'text' => '企业认证管理',
            //     'url' => url('Member/enterprise_list')
            // ),
            // array(
            //     'name' => 'lockup',
            //     'text' => '违规企业认证',
            //     'url' => url('Member/enterprise_list', ['type' => 'lockup'])
            // ),
            array(
                'name' => 'waitverify',
                'text' => '企业认证审核',
                'url' => url('Member/enterprise_list', ['type' => 'waitverify'])
            ),
        );
        if (request()->action() == 'add' || request()->action() == 'member' || request()->action() == 'enterprise_list') {
            $menu_array[] = array(
                'name' => 'add',
                'text' => '添加客户',
                'url' => "javascript:dsLayerOpen('" . url('Member/add') . "','" . lang('ds_add') . "')"
            );
        }
        return $menu_array;
    }

}

?>
